﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pavilion.Control
{
    public class ChainControl<T>
    {
        private IChain<T> parent, user;
        private NotifiableCollection<T> userCollection;

        public ChainControl(NotifiableCollection<T> userCollection, IChain<T> user)
        {
            this.user = user;
            this.userCollection = userCollection;

            if (userCollection != null)
            {
                userCollection.Removed += (T item, int index) => { ((IChain<T>)item).ChainControl.SetParent(null); };
                userCollection.Added += (T item, int index) => { AssociateUserAsParentOfThisItem((IChain<T>)item); };
            }

            LoadCollection(userCollection);
        }

        private void LoadCollection(NotifiableCollection<T> userCollection)
        {
            if (userCollection == null)
                return;

            foreach (object item in userCollection)
                AssociateUserAsParentOfThisItem((IChain<T>)item);
        }

        private void SetParent(IChain<T> parent)
        {
            this.parent = parent;
        }

        private void DetachItemFromParent(IChain<T> item)
        {
            IChain<T> parentOfItem = item.ChainControl.Parent;

            if (parentOfItem != null)
                parentOfItem.ChainControl.userCollection.Remove((T)item);
        }

        private void AssociateUserAsParentOfThisItem(IChain<T> item)
        {
            DetachItemFromParent(item);
            item.ChainControl.SetParent(user);
        }

        /// <summary>
        /// Gets the Parent.
        /// </summary>
        public IChain<T> Parent
        {
            get { return parent; }
        }
    }
}
